package org.kca.graphics;

import java.util.Arrays;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

/**
 * The MainFrame class implements a full screen game engine. 
 * @author ctheng
 *
 */
public class MainFrame extends GameCore
{
	/** The current screen controller. Must be set to run the game */
	private IController controller;
	private boolean[] buttonState;
	
	public MainFrame(){
		super();
		buttonState = new boolean[3];
		Arrays.fill(buttonState, false);
	}
	
	/**
	 * Sets the controller which is the main object responsible for drawing the screen
	 * and receiving events. The controller must be set before run() can be called
	 * @param c the controller to set
	 */
	public void setController(IController c)
	{
	    controller = c;
	}	
	
	// see superclass
	public void draw()
	{
		if (controller != null)
		{
		    controller.drawComponent(0, 0);
		}
	}
	
	// see superclass
	public void update(long elapsedTime)
	{
	    checkInputDevices();
	    if (controller != null)
	    {
	        controller.update(elapsedTime);
	    }
	}
	
	@Override
	public void run()
	{
	    if (controller != null)
	    {
	        super.run();
	    }
	}
	
	private void checkInputDevices()
    {
        while (Keyboard.next())
        {
            if (controller != null)
            {
                int key = Keyboard.getEventKey();
                int echar = Keyboard.getEventCharacter();
                if (Keyboard.getEventKeyState())
                {
                    controller.keyPressed(key, echar);
                }
                else
                {
                    controller.keyReleased(key, echar);
                }
            }
        }
        while (Mouse.next())
        {
            if (controller != null)
            {
                int mbut = Mouse.getEventButton();
                if (mbut >= 0)
                {
                    if (Mouse.getEventButtonState())
                    {
                        buttonState[mbut] = true;
                        controller.mousePressed(mbut, Mouse.getEventX(), getHeight() - Mouse.getEventY());
                    }
                    else
                    {
                        buttonState[mbut] = false;
                        controller.mouseReleased(mbut, Mouse.getEventX(), getHeight() - Mouse.getEventY());
                    }
                }
            }
        }
    }
	
	/**
	 * Gets the mouse X coordinate
	 * @return the x coordinate of the mouse
	 */
	public int getMouseX()
	{
	    return Mouse.getX();
	}
	
	/**
	 * Gets the mouse Y coordinate
	 * @return the y coordinate of the mouse
	 */
	public int getMouseY()
	{
	    /*
	     * This fix is needed because LWJGL treats bottom left as (0, 0) 
	     */
	    return getHeight() - Mouse.getY();
	}
}
